package com.softwin.cryptocurrency.demo.test;

import com.softwin.cryptocurrency.demo.security.JwtCallCredential;
import com.softwin.grpc.common.Common;
import com.softwin.marketdata.gateway.service.MarketDataManageGrpc;
import com.softwin.order.reporting.service.*;
import io.grpc.ConnectivityState;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by nirui.
 */
public class MarketMaker {
//    private String tgHost = "47.74.46.27"; //服务器地址
    private String tgHost = "192.168.1.162"; //服务器地址
    private String mgHost = "47.91.18.148"; //服务器地址
    private OrderReportingGrpc.OrderReportingStub tgStub; //交易网关
    private MarketDataManageGrpc.MarketDataManageStub mgStub; //行情网关
    QueryServiceGrpc.QueryServiceBlockingStub queryServiceStub;
    private Common.Symbol btcusdtSymbol; //交易币对
    private String subaccountCode = "huobi_a_001"; //子账号
    private String username = "openTrader"; //交易员用户名
    private String password = "66666"; //交易员密码
    private String quantity = "0.001"; //下单量
    private static int interval = 1000 * 60 * 10;
    public static void main(String[] args)  throws InterruptedException {
        MarketMaker cma = new MarketMaker();
        int i = 1;
        while(true){
            cma.querySymbol();
            Thread.sleep(interval * i++);
        }
    }

    /**
     * 简单的做市策略，在盘口上下1%进行挂单
     * 在挂单和已有订单价格相差超过0.3%时，调整订单价格。
     */
    private MarketMaker(){
        ManagedChannel mgChannel = ManagedChannelBuilder.forAddress(mgHost, 8991).usePlaintext().build();
        //初始化行情网关
        mgStub = MarketDataManageGrpc.newStub(mgChannel);
        ManagedChannel tgChannel = ManagedChannelBuilder.forAddress(tgHost, 8993)
                .keepAliveTime(15, TimeUnit.MINUTES).usePlaintext().build();

        //登录获取token
        LoginGrpc.LoginBlockingStub loginBlockingStub = LoginGrpc.newBlockingStub(tgChannel);
        LoginOuterClass.RspLogin rspLogin = loginBlockingStub.login(LoginOuterClass.ReqLogin.newBuilder().setUsername(username).setPassword(password).build());
        String token = rspLogin.getToken();
        //初始化交易网关和查询网关
        tgStub = OrderReportingGrpc.newStub(tgChannel).withCallCredentials(new JwtCallCredential(token));
        queryServiceStub = QueryServiceGrpc.newBlockingStub(tgChannel).withCallCredentials(new JwtCallCredential(token));

        Runnable stateListener = new Runnable() {
            @Override public void run() {
                ConnectivityState currentState = tgChannel.getState(true);
                System.out.println("state change: " + currentState);
                // 根据最新状态进行处理
                switch (currentState){
                    case IDLE: //服务器断开了
                        //TODO 停止策略，或者暂停策略，等待连接成功后再恢复
                        break;
                    case READY: //连接建立成功
                        //TODO 进行重新初始化
                        break;
                    case SHUTDOWN: //客户端主动断开
                        //可以忽略
                        break;
                    case CONNECTING: // 正在尝试重连
                        //可以忽略
                        break;
                    case TRANSIENT_FAILURE: //重连失败
                        //可以忽略，还会继续尝试重连的
                        break;
                    default:
                        break;
                }
                tgChannel.notifyWhenStateChanged(currentState, this);
            }
        };
        stateListener.run();
    }

    private void querySymbol(){
        //订阅成交回报
        try {

        Orderreporting.SymbolResponse symbols = queryServiceStub.getSymbols(Orderreporting.SymbolRequest.newBuilder().setSymbol(Common.Symbol.newBuilder().setExchangeType("dummy").build()).build());
        System.out.println(new Date() + symbols.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

